package com.zyl.widget.timer;

import java.util.Timer;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.RemoteViews;

public class BaseWidget extends AppWidgetProvider {

	public static final String START_ACTION = "com.zyl.widget.start";
	static long time = 0;

	@Override
	public void onUpdate(Context context, AppWidgetManager appWidgetManager,
			int[] appWidgetIds) {
		int i = appWidgetIds.length;

		for (int j = 0; j < i; j++) {
			new Timer().scheduleAtFixedRate(new MyTimerTask(context,
					appWidgetManager, appWidgetIds[j]), 1L, 1L);

		}

		super.onUpdate(context, appWidgetManager, appWidgetIds);
	}

	public static void updateAppWidget(Context context,
			AppWidgetManager appWidgetManager, int appWidgetId) {

		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.widget);

		int ms = (int) (time % 1000);
		int sec = (int) (time / 1000 % 60);
		int min = (int) (time / 60000 % 60);
		int hour = (int) (time / 3600000);

		// long hour = time / (60 * 60 * 1000);
		// long min = (time - hour * (60 * 60 * 1000)) / (60 * 1000);
		// long sec = (time - hour * (60 * 60 * 1000) - min * (60 * 1000)) /
		// 1000;
		// long ms = time - hour * (60 * 60 * 1000) - min * (60 * 1000) - sec
		// * 1000;

		remoteViews.setTextViewText(R.id.sec, hour + ":" + min + ":" + sec);
		remoteViews.setTextViewText(R.id.ms, ms + "");

		Intent intentClick = new Intent(
				AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		intentClick.putExtra("appWidgetId", appWidgetId);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intentClick, 0);
		remoteViews.setOnClickPendingIntent(R.id.Base, pendingIntent);
		appWidgetManager.updateAppWidget(appWidgetId, remoteViews);
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		super.onReceive(context, intent);
		if (intent.getExtras() != null) {
			if (intent.getExtras().containsKey("appWidgetId")) {
				// int appWidgetId = (Integer)
				// intent.getExtras().get("appWidgetId");
				String[] config = BaseConf.loadPref(context);
				try {
					long t = Long.parseLong(config[1]);
					if (time % t > (t - 10000)) {
						time += t;
					} else {
						time = t;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		AppWidgetManager appWidgetManager = AppWidgetManager
				.getInstance(context);
		int[] appWidgetIds = appWidgetManager
				.getAppWidgetIds(new ComponentName(context, BaseWidget.class));
		onUpdate(context, appWidgetManager, appWidgetIds);

	}

}